/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28
 */
package com.tzinfo.tzb;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ForumRecommend;
import com.tzinfo.tzb.domain.ForumRecommend.ForumRecommendData;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TzbMyPostActivity extends TzbBaseActivity implements
        IXListViewListener, RadioGroup.OnCheckedChangeListener {
    // 标志

    // 参数

    // 适配器
    private ImageAdapter imageAdapter;

    // 数据
    private List<Map<String, Object>> data;
    private ForumRecommend forumRecommend;

    // UI组件
    private YXWXListView listView;
    private RelativeLayout layout_no_listdata;

    // 其他
    private Handler mHandler;
    public static TzbMyPostActivity activity;
    private int page = 1; // 页码
    private int pagesize = 15; // 每页条数
    private TextView text_title;
    private RadioGroup bottombar;

    /*
    "http://tzt.tzinfo.net/mob/api/ForumpostListM.ashx" ,我的帖子
    "http://tzt.tzinfo.net/mob/api/ForumthreadListM.ashx" ,我的主题
     */
    private String requestUrl="http://tzt.tzinfo.net/mob/api/ForumthreadListM.ashx";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        activity = this;
        setContentView(R.layout.tzb_ac_my_posts);
        text_title = (TextView) findViewById(R.id.text_title);
        text_title.setText("我的帖子");
        initParameter();
        initAnimation();
        initUI();
        initData();
        listView.setSelection(0);
        // listView.post(new Runnable() {
        // @Override
        // public void run() {
        // listView.smoothScrollToPosition(TzbDynamicData.POSITION);
        // }
        // });
    }

    private void initParameter() {
        mHandler = new Handler();
    }

    private void initAnimation() {
    }

    private void initUI() {
        // 加载滚动进入条
        mProgressBar = (ProgressBar) this.findViewById(R.id.progressbar_loding);
        listView = (YXWXListView) ResFinder
                .findViewById(this, "R.id.xListView");
        layout_no_listdata = (RelativeLayout) ResFinder.findViewById(this,
                "R.id.layout_no_listdata");

        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterview, View view,
                                    int i, long l) {
                Intent intent = new Intent(TzbMyPostActivity.this, PostActivity2.class);
                Bundle bundle = new Bundle();
                bundle.putInt("tid", forumRecommend.getData().get((int) l).getTid());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        bottombar = (RadioGroup) findViewById(R.id.bottombar_container);

        bottombar.setOnCheckedChangeListener(this);
    }

    private void initData() {
        if (forumRecommend == null
                || !forumRecommend.isSuccess()) {
            requestInfo();
        } else {
            initListView();
        }
    }

    private void initListView() {
        // 初始化data
        if (data == null) {
            data = new ArrayList<Map<String, Object>>();
        } else {
            data.clear();
        }
        List<ForumRecommendData> list = forumRecommend.getData();
        if (list == null || list.size() == 0) {
            layout_no_listdata.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        } else {
            layout_no_listdata.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                String Avatar = "";
                if (list.get(i).getAttachment() == null
                        || list.get(i).getAttachment().size() == 0) {
                    Avatar = list.get(i).getUserinfo().getAvatar();
                } else {
                    Avatar = list.get(i).getAttachment().get(0).getAttachment();
                }
                map.put("Avatar", Avatar);
                String subject = list.get(i).getSubject();
                if (subject != null && subject.length() >= 12) {
                    subject = subject.substring(0, 12) + "…";
                }

                map.put("Subject", subject);
                String netname = list.get(i).getUserinfo().getNetname();
                if (netname == null || "".equals(netname.trim())) {
                    netname = list.get(i).getUserinfo().getUsername();
                }
                // 设置几秒前、几分前、几小时前等
                String sDateline = YXWDateUtil.getTimeInterval(list.get(i).getUserinfo().getRegdate(), "MM/dd/yyyy HH:mm:ss");
                map.put("Dateline", sDateline);
                map.put("Netname", netname);
                map.put("Credits", list.get(i).getUserinfo().getCredits());
                data.add(map);
            }
            if (imageAdapter == null) {
                imageAdapter = new ImageAdapter(TzbMyPostActivity.this,
                        data, ResFinder.getR(TzbMyPostActivity.this,
                        "R.layout.tzb_item_tuijian"), new String[]{
                        "Avatar", "Subject", "Dateline", "Netname",
                        "Credits"}, new int[]{
                        ResFinder.getR(TzbMyPostActivity.this,
                                "R.id.list_item_image"),
                        ResFinder.getR(TzbMyPostActivity.this,
                                "R.id.list_item_title"),
                        ResFinder.getR(TzbMyPostActivity.this,
                                "R.id.list_item_time"),
                        ResFinder.getR(TzbMyPostActivity.this,
                                "R.id.list_item_netname"),
                        ResFinder.getR(TzbMyPostActivity.this,
                                "R.id.list_item_credits")});
                listView.setAdapter(imageAdapter);
            } else {
                imageAdapter.notifyDataSetChanged();
            }
        }
    }

    // 重载，默认请求新数据
    private void requestInfo() {
        requestInfo(TzbCommonData.NOPULL_LOAD);
    }

    private void requestInfo(int type) {
        final int type2 = type;
        if (type == TzbCommonData.NOPULL_LOAD) {
            showProgressBar();
        }
        String url = requestUrl
                + "?author="
                + TztData.userInfo.getData().getUserName()
                + "&type=1" + "&sessionid="
                + TztData.userInfo.getData().getSessionID()
                + "&Page="
                + page
                + "&displayorder=0"
                + "&Pagesize="
                + pagesize;
        OutLog.LogE("url", url);
        getData(type2, url);

    }

    private void getData(final int type2, String url) {
        GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
        galHttpRequest.setCacheEnable(false);
        galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<ForumRecommend>() {
                }.getType();

                forumRecommend = gson.fromJson(arg0, type);
                if (forumRecommend.isSuccess()) {
                    if (type2 == TzbCommonData.PULL_LOAD_MORE) {
                        int size = forumRecommend.getData().size();
                        for (int i = 0; i < size; i++) {
                            forumRecommend.getData().add(
                                    forumRecommend.getData().get(i));
                        }
                        if (size < pagesize) {
                            listView.setPullLoadEnable(false);
                            Toast.makeText(TzbMyPostActivity.this,
                                    "已经是最后一页！", Toast.LENGTH_LONG).show();
                        }
                    } else if (type2 == TzbCommonData.PULL_REFLASH
                            || type2 == TzbCommonData.NOPULL_LOAD) {
                        if (forumRecommend.getData().size() < 10) {
                            listView.setPullLoadEnable(false);
                        } else {
                            listView.setPullLoadEnable(true);
                        }

                    }
                    initListView();
                    onLoadFinish();
                } else {
                    Toast.makeText(TzbMyPostActivity.this, "数据加载失败…",
                            Toast.LENGTH_LONG).show();
                }
                removeProgressBar();
            }
        });
    }

    private void onLoadFinish() {
        listView.stopRefresh();
        listView.stopLoadMore();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        listView.setRefreshTime(df.format(new Date()));
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                requestInfo(TzbCommonData.PULL_REFLASH);
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                requestInfo(TzbCommonData.PULL_LOAD_MORE);
            }
        }, 2000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == 1) {
                boolean isReflash = data.getBooleanExtra(TzbCommonData.IS_NEED_REFLASH, false);
                if (isReflash) {
                    requestInfo();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        setCurrentItem(checkedId);
    }

    public void setCurrentItem(int checkedId) {
        listView.setPullLoadEnable(true);
        page=1;
        switch (checkedId) {
            case R.id.my_theme_check:
                 requestUrl="http://tzt.tzinfo.net/mob/api/ForumthreadListM.ashx";
                break;
            case R.id.my_post_check:
                requestUrl="http://tzt.tzinfo.net/mob/api/ForumpostListM.ashx";
                break;
        }
        showProgressBar();
        requestInfo(TzbCommonData.PULL_REFLASH);
    }
}
